﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace LiveWriterBackupWPF
{
    public static class Updates
    {
        public static bool CheckForUpdates(out string updateUrl)
        {
        
            string checkForUpdatesUrl = @"http://www.scottisafool.co.uk/WLBackup/Version.xml";
            try
            {
                Version newVersion = null;
                WLBDebug.WriteToFile("Loading XML file to check for updates.");
                XDocument doc = XDocument.Load(checkForUpdatesUrl);
                var update = from updates in doc.Descendants("WLBackup")
                             select new
                             {
                                 CurrentVersion = updates.Element("CurrentVersion").Value,
                                 InstallURL = updates.Element("InstallURL").Value,
                             };
                string tempurl = "";
                foreach (var u in update)
                {
                    tempurl = u.InstallURL;
                    newVersion = new Version(u.CurrentVersion);
                }
                Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                if (curVersion.CompareTo(newVersion) < 0)
                {
                    updateUrl = tempurl;
                    WLBDebug.WriteToFile("A newer version (" + newVersion.ToString() + ") is available.");
                    return true;
                }
                else
                {
                    updateUrl = "";
                    WLBDebug.WriteToFile("Software is up-to-date.");
                    return false;
                }
            }
            catch (Exception ex)
            {
                WLBDebug.WriteToFile(ex.Message);
                WLBDebug.WriteToFile(ex.ToString());
                updateUrl = ex.Message;
                return false;
            }
        }
    }
}
